﻿using shop.Bll;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using unvell.ReoGrid;
using shop.Bll.Logi;
using CommonTools;
using CommonTools.Controls;
using unvell.ReoGrid.CellTypes;

namespace shop.Logi
{
    public partial class LogisticsBillForm : DockContent
    {

        shop.Bll.Logi.LogisticsBillBll _bll = new LogisticsBillBll();


        public LogisticsBillForm()
        {
            InitializeComponent();

            this.box_begin.Value = DateTime.Today.AddMonths(-1);
            this.box_end.Value = DateTime.Today;
        }

        /// <summary> 导入 </summary>
        private async void btn_import_Click(object sender, EventArgs e)
        {
            var bl = InputBox.GetValue("请填写导入的月份", DateTime.Today, "系统提示", out var month, "yyyy-MM");
            if (bl == false)
            {
                MessageTip.ShowWarning(this, "已取消");
                return;
            }

            month = new DateTime(month.Year, month.Month, 1);

            //var res = await WaitUI.RunAsync(async () => await Task.Run( ImportExcel));
            //var res = await WaitUI.RunAsync(async () => await ImportExcel());
            //MessageBox.Show(res, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);

            var reader = new ExcelHelper();
            var config = reader.GetReadConfig();
            if (config.Stop)
            {
                //return "取消";

                MessageBox.Show("取消", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var res =  await WaitUI.RunAsync(async () => await this.ImportExcel(config, reader, month));
            MessageBox.Show(res, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);

            ////////////////////////////////////////////////////////////////////////

            //var dt = ExcelHelper.Import();

            //if (res == null)
            //{
            //    return;
            //}

            // id, 类别,  账单日期	物流单号	目的地省	目的地市	重量	结算重量	运费	加收1	加收2	加收3	加收4	总运费	预付单号钱	需结算运费, 快递老板


            //读取明细数据, 
            ////var cl_logiCompany = dt.Columns[2];
            //var cl_date = dt.Columns[2];
            //var cl_logiNo = dt.Columns[3];  //快递单号
            //var cl_Prov = dt.Columns[4];  //省
            //var cl_city = dt.Columns[5];  //城市
            //var cl_logiNWei = dt.Columns[6];  //重量
            //var cl_logiBillWei = dt.Columns[7];  //结算重量
            //var cl_logiFee = dt.Columns[8];  //运费
            //var cl_addFee1 = dt.Columns[9];  //加收1
            //var cl_addFee2 = dt.Columns[10];  //加收2
            //var cl_addFee3 = dt.Columns[11];  //加收3
            //var cl_addFee4 = dt.Columns[12];  //加收4
            //var cl_total = dt.Columns[13];  //总费用
            //var cl_PrevPay = dt.Columns[14];  //预付单号钱
            //var cl_Payable = dt.Columns[15];  //需结算运费
            //var cl_logiAcct = dt.Columns[16];  //快递老板


            //foreach (DataColumn item in dt.Columns)
            //{
            //    if (item.Caption.Contains("总费用"))
            //    {
            //        cl_total = item;
            //    }
            //}
            //var cl_shop = dt.Columns[5];  //店铺

            //var items = dt.AsEnumerable()
            //        .Select(a => new
            //        {
            //            //logiCompany = a.Field<string>(cl_logiCompany.ColumnName)?.IsNull(),
            //            occurDate = a.Field<string>(cl_date.ColumnName)?.IsNullDate(null),
            //            logiNo = a.Field<string>(cl_logiNo.ColumnName),
            //            prov = a.Field<string>(cl_Prov.ColumnName),
            //            city = a.Field<string>(cl_city.ColumnName),
            //            weight = a.Field<string>(cl_logiNWei.ColumnName).IsNull(0m),
            //            billWeight = a.Field<string>(cl_logiBillWei.ColumnName).IsNull(0m),
            //            logiFee = a.Field<string>(cl_logiFee.ColumnName).IsNull(0m),
            //            addFee1 = a.Field<string>(cl_addFee1.ColumnName).IsNull(0m),
            //            addFee2 = a.Field<string>(cl_addFee2.ColumnName).IsNull(0m),
            //            addFee3 = a.Field<string>(cl_addFee3.ColumnName).IsNull(0m),
            //            addFee4 = a.Field<string>(cl_addFee4.ColumnName).IsNull(0m),
            //            total = a.Field<string>(cl_total.ColumnName).IsNull(0m),
            //            prevPay = a.Field<string>(cl_PrevPay.ColumnName).IsNull(0m),
            //            payable = a.Field<string>(cl_Payable.ColumnName).IsNull(0m),
            //            logiAcct = a.Field<string>(cl_logiAcct.ColumnName),
            //        })
            //        .Select(a => new LogisticsBillItem()
            //        {
            //            //LogisticsCompany = a.logiCompany,
            //            LogiAcct = a.logiAcct,
            //            LogisticsBillExcelId = 0,
            //            DeliveryTime = a.occurDate,
            //            LogisticCode = a.logiNo,
            //            ReceiveCity = a.city,
            //            ReceiveProvince = a.prov,

            //            DeliveryWeight = a.weight,
            //            BillWeight = a.billWeight,
            //            Freight = a.logiFee,
            //            AddFee1= a.addFee1,
            //            AddFee2= a.addFee2,
            //            AddFee3= a.addFee3,
            //            AddFee4= a.addFee4,

            //            //ShopName = a.shop,
            //            TotalFee = a.total,
            //            PrevPay=a.prevPay,
            //            Payable=a.payable, 

            //            Other = 0,
            //            BillFlag ="快递账单",
            //        })
            //        .ToList();

            //var res = await _bll.SaveItems(items, UserBll.CurrentUser);
            //if (res.IsOk)
            //{
            //    MessageTip.ShowOk(this, "导入完成");
            //}
            //else
            //{
            //    MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
        }


        private async Task<string> ImportExcel(SheetReadConfig config, ExcelHelper helper, DateTime month )
        {

            var items = helper.ReadSheet(config)
                   .Select(a => new
                   {
                       occurDate = a[2]?.IsNullDate(null),
                       logiNo = a[3]?.ToString(),
                       prov = a[4]?.ToString(),
                       city = a[5]?.ToString(),
                       weight = a[6].IsNull(0m),
                       billWeight = a[7].IsNull(0m),
                       logiFee = a[8].IsNull(0m),
                       addFee1 = a[9].IsNull(0m),
                       addFee2 = a[10].IsNull(0m),
                       addFee3 = a[11].IsNull(0m),
                       addFee4 = a[12].IsNull(0m),
                       total = a[13].IsNull(0m),
                       prevPay = a[14].IsNull(0m),
                       payable = a[15].IsNull(0m),
                       logiAcct = a.Length > 16 ? a[16]?.ToString() : string.Empty,
                   })
                   .Select(a => new LogisticsBillItem()
                   {
                       FMonth= month,
                       //LogisticsCompany = a.logiCompany,
                       LogiAcct = a.logiAcct,
                       LogisticsBillExcelId = 0,
                       DeliveryTime = a.occurDate,
                       LogisticCode = a.logiNo,
                       ReceiveCity = a.city,
                       ReceiveProvince = a.prov,

                       DeliveryWeight = a.weight,
                       BillWeight = a.billWeight,
                       Freight = a.logiFee,
                       AddFee1 = a.addFee1,
                       AddFee2 = a.addFee2,
                       AddFee3 = a.addFee3,
                       AddFee4 = a.addFee4,

                       //ShopName = a.shop,
                       TotalFee = a.total,
                       PrevPay = a.prevPay,
                       Payable = a.payable,

                       Other = 0,
                       BillFlag = "快递账单",
                   });

            //分块存储到数据库
            int c = 0;
            LogisticsBillItem[] arr = new LogisticsBillItem[1000];
            //int k = 0;
            foreach (var item in items)
            {
                arr[c++] = item;

                if (c >= 1000)
                {
                    //k++;

                    var res = await _bll.SaveItems(arr, UserBll.CurrentUser);
                    if (!res.IsOk)
                    {
                        return res.Message;
                    }
                    //清零
                    c = 0;
                    arr = new LogisticsBillItem[1000];
                }
            }

            // 结尾
            var temp = arr.Take(c).ToList();
            var res1 = await _bll.SaveItems(temp, UserBll.CurrentUser);
            if (res1.IsOk || c ==0)
            {
                return "导入完成";
            }
            else
            {
                return res1.Message;
            }
        }


        private void btn_Query_Click(object sender, EventArgs e)
        {
            turnPageBox1_PageChanged(1, turnPageBox1.PageSize); //重新查询第一页
        }


        private async void turnPageBox1_PageChanged(int index, int pageSize)
        {
            var begin = box_begin.Value.Value;
            var end = box_end.Value.Value;
            this.btn_deleteRepeat.Enabled = false;


            await WaitUI.RunAsync (async () =>
            {
                var res = await _bll.Query(begin, end, this.box_find.Text.Trim(), index, pageSize);

                if (res.IsOk)
                {
                    new GridDataBuilder(this.grid1)
                        .UseData(res.Data)
                        .AutoCreateColumns()
                        .UseFilter()
                        .End();

                    if (index == 1)
                    {
                        this.turnPageBox1.Reset(res.Rows);
                    }
                }
                else
                {
                    MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            });

        }

        private async void btn_delete_Click(object sender, EventArgs e)
        {
            var begin = box_begin.Value.Value.ToString("yyyy-MM-dd");
            var end = box_end.Value.Value.ToString("yyyy-MM-dd");

            if (MessageBox.Show($"确认要删除从{begin} 到 {end} 范围内的所有账单数据?", 
                Properties.Resources.systemInformation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var res = await _bll.DeleteItems(box_begin.Value.Value, box_end.Value.Value);
                if (res.IsOk) 
                {
                    MessageTip.ShowOk(this, "删除完成");
                }
                else
                {
                    MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary> 物流费用导入 </summary>
        private async void btn_import2_Click(object sender, EventArgs e)
        {
            var bl = InputBox.GetValue("请填写导入的月份", DateTime.Today, "系统提示", out var month,"yyyy-MM");
            if (bl == false)
            {
                MessageTip.ShowWarning(this, "已取消");
                return;
            }

            var dt = ExcelHelper.Import();

            if (dt == null)
            {
                return;
            }

            //读取明细数据, 
            var cl_logiAcct = dt.Columns[0];  //快递老板
            var cl_logiNo = dt.Columns[1];  //快递单号
            var cl_Remarks= dt.Columns[2];  //费用明细
            var cl_fee = dt.Columns[3];  //费用


            var items = dt.AsEnumerable()
                    .Select(a => new
                    {
                        logiNo = a.Field<string>(cl_logiNo.ColumnName),
                        logiAcct = a.Field<string>(cl_logiAcct.ColumnName),
                        remarks = a.Field<string>(cl_Remarks.ColumnName),
                        fee = a.Field<string>(cl_fee.ColumnName).IsNull(0m),
                    })
                    .Select(a => new LogisticsBillItem()
                    {
                        LogisticsBillExcelId = 0,
                        LogisticCode = a.logiNo,
                        LogiAcct = a.logiAcct,
                        TotalFee = a.fee,
                        Other = 0,
                        BillFlag = "物流费用",
                        DeliveryTime = month,
                        FMonth= month,
                        Remarks= a.remarks,
                    })
                    .ToList();

            var res = await _bll.SaveItems(items, UserBll.CurrentUser);
            if (res.IsOk)
            {
                MessageTip.ShowOk(this, "导入完成");
            }
            else
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private async void btn_feeReport_Click(object sender, EventArgs e)
        {
            this.btn_deleteRepeat.Enabled = false;


            var res = await WaitUI.RunAsync(async () => await _bll.QueryFeeReport(this.box_begin.Value.Value, this.box_end.Value.Value));

            if (res.IsOk)
            {
                new GridDataBuilder(this.grid1)
                    .UseData(res.Data)
                    .AutoCreateColumns()
                    .UseFilter()
                    .End();
      
            }
            else
            {
                MessageBox.Show("没有查询到数据", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private async void btn_logiBillRpt_Click(object sender, EventArgs e)
        {
            this.btn_deleteRepeat.Enabled = false;

            var res = await WaitUI.RunAsync(async () => await _bll.QueryBillReport(this.box_begin.Value.Value, this.box_end.Value.Value));

            if (res.IsOk)
            {
                new GridDataBuilder(this.grid1)
                    .UseData(res.Data)
                    .AutoCreateColumns()
                    .UseFilter()
                    .End();

            }
            else
            {
                MessageBox.Show("没有查询到数据", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private async void btn_queryRepeat_Click(object sender, EventArgs e)
        {
            this.btn_deleteRepeat.Enabled = false;

            var res = await WaitUI.RunAsync(async () => await _bll.QueryRepeat(this.box_begin.Value.Value, this.box_end.Value.Value));

            if (res?.Any() == true)
            {
                new GridDataBuilder(this.grid1)
                    .UseData(res)
                    .AutoCreateColumns()
                    .UseFilter()
                    .End();

                //var sht = grid1.CurrentWorksheet;
                //for (int i = 1; i <= res.Count(); i++)
                //{
                //    sht[i, 0] = new CheckBoxCell();
                //}

                MessageTip.ShowOk(this, "查询完成");
                this.btn_deleteRepeat.Enabled = true;
            }
            else
            {
                MessageBox.Show("没有查询到数据", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private async void btn_deleteRepeat_Click(object sender, EventArgs e)
        {
            var list = new List<int>();
            //var rows = new List<int>(); 

            int i = 1;
            while (true)
            {
                if (string.IsNullOrEmpty(grid1[1,i]?.ToString()) )
                {
                    break;
                }

                if (grid1[0,i].IsNull(false) == true)
                {
                    list.Add(grid1[1, i].IsNull(0));
                    //rows.Add(i);
                }
                i++;
            }

            if (list.Count == 0)
            {
                MessageBox.Show("没有选择项目!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (MessageBox.Show($"确认要删除所选账单: 共计{list.Count}条", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information)== DialogResult.OK)
                {
                    await _bll.Delete(list);
                    MessageTip.ShowOk(this, "删除完成, 当前界面请手动刷新!");

                    //界面中删除 
                    
                }
            }

        }
    }
}
